// 购物车模块
import Storage from '@/untils/storage.js'
const cart = {
	state() {
		return {
			cart: [
				// {
				// goods_id: "商品id",
				// num: "购买数量",
				// attr_id: "属性id",
				// price: "单价",
				// thumn: "商品图片",
				// goods_name: "商品名",
				// goods_descript: "商品描述"
			// }, 
			]
		}
	},
	mutations: {
		addGoods(state, goods) {
			// state.goodsNumber++
			goods.checked = false;
			// 判断一下cart是否已经有这个商品了
			if (state.cart.length == 0) {
				state.cart.push(goods)
			} else {
				let isHas = false;
				for (let i = 0; i < state.cart.length; i++) {
					const cartElem = state.cart[i];
					if (goods.goods_id == cartElem.goods_id && goods.attr_id == cartElem.attr_id) {
						state.cart[i].num++;
						isHas = true;
					}
				}
				if (!isHas) {
					state.cart.push(goods)
				}
			}
			// 将添加好的商品存储到缓存中
			Storage.set('cartGoods',state.cart);
		},
		setGoodsChecked(state,index){
			// 将商品锁定状态为相反
			state.cart[index].checked = !state.cart[index].checked;
			Storage.set('cartGoods',state.cart);
		},
		addGoodsNum(state,index){
			state.cart[index].num++;
			Storage.set('cartGoods',state.cart);
		},
		subGoodsNum(state,index){
			if(state.cart[index].num>1){
				state.cart[index].num--;
			}
			Storage.set('cartGoods',state.cart);
		},
		changeCartChecked(state,statue){
			for (let i = 0; i < state.cart.length; i++) {
				state.cart[i].checked = !statue;
			}
			Storage.set('cartGoods',state.cart);
		},
		storageToCart(state,goodscart){
			state.cart = goodscart
		},
	},
	actions: {},
	getters: {
		cartGoodsNumber(state) {
			let countGoodsNum = 0;
			for (let i = 0; i < state.cart.length; i++) {
				let cartElem = state.cart[i]
				countGoodsNum += cartElem.num;
			}
			return countGoodsNum;
		},
		cartGoodsTotal(state){ //计算购物车选中商品总价
			let total = 0;
			for(let i = 0; i<state.cart.length;i++){
				let cartElem = state.cart[i];
				if(cartElem.checked){
					total += cartElem.num*cartElem.price
				}
			}
			return total
		},
		cartAllChecked(state){
			let all = false;
			let count = 0;
			for(let i = 0; i<state.cart.length;i++){
				let cartElem = state.cart[i];
				if(cartElem.checked){
					count++;
				}
			}
			if(state.cart.length == count){
				all = true
			}
			if(state.cart.length == 0){
				all = false
			}
			return all;
		}
	},
}

export default {
	cart
}
